import { Injectable } from '@nestjs/common';
import { sum } from 'lodash';
import { PrismaService } from 'src/prisma/prisma.service';

@Injectable()
export class CalculatePointAcrossService {
  constructor(private prisma: PrismaService) {}

  async calculate(args: Record<string, any>) {
    const { zoneId } = args;

    const zone = await this.prisma.zone.findUnique({
      where: { id: +zoneId },
      include: {
        across: true,
        bets: true,
      },
    });

    const { across, bets } = zone;

    // 删除数据
    await this.prisma.pointAcross.deleteMany({
      where: { across: { zoneId: +zoneId } },
    });

    const pointAcrossArr = across.map((item) => {
      const betIndex = bets.findIndex((b) => b.btName === item.btName);
      const btSpanArr = bets
        .filter((_, index) => index < betIndex)
        .map((b) => b.btSpan);
      const lei = sum(btSpanArr);
      const x = lei + item.acrossX;
      const y = item.acrossY + item.controlHeight;
      return { x, y, calcX: x / 5, calcY: y * 2, acrossId: item.id };
    });

    await this.prisma.pointAcross.createMany({ data: pointAcrossArr });

    return pointAcrossArr;
  }
}
